import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'dart:developer' as developer;

import '../api/user_api.dart';
import '../models/index.dart';

/// 用户服务 - 管理用户信息和登录状态
class UserService extends GetxService {
  static UserService get to => Get.find();

  final _storage = GetStorage();
  
  // 用户信息状态 (响应式)
  final Rx<UserData?> _currentUser = Rx<UserData?>(null);
  final RxBool _isLoggedIn = false.obs;

  // Getters
  UserData? get currentUser => _currentUser.value;
  bool get isLoggedIn => _isLoggedIn.value;
  String get userId => currentUser?.userid.toString() ?? '';
  String get userName => currentUser?.username ?? '';
  String get userPhone => currentUser?.userPhone ?? '';
  String get userAvatar => currentUser?.userAvatarUrl ?? '';
  int get userPoints => currentUser?.userPoints ?? 0;
  int get userLevel => currentUser?.userLevel ?? 0;
  String get userSignature => currentUser?.userSignature ?? '';
  List<String> get userTags => currentUser?.userTags ?? [];
  String? get rongCloudToken => currentUser?.rongCloudToken;
  String? get rongCloudUserId => currentUser?.rongCloudUserId;

  // 存储键名
  static const String _userInfoKey = 'user_info';
  static const String _loginStatusKey = 'is_logged_in';

  @override
  void onInit() {
    super.onInit();
    developer.log('UserService初始化');
    _loadUserFromStorage();
  }

  /// 从本地存储加载用户信息
  void _loadUserFromStorage() {
    try {
      final userData = _storage.read<Map<String, dynamic>>(_userInfoKey);
      final isLoggedIn = _storage.read<bool>(_loginStatusKey) ?? false;

      developer.log('🔍 ================ 本地存储加载调试 ================');
      developer.log('📊 userData存在: ${userData != null}');
      developer.log('🔐 登录状态: $isLoggedIn');
      
      if (userData != null) {
        developer.log('📦 原始userData内容预览: ${userData.keys.take(10).toList()}');
        
        // 检查关键字段
        developer.log('📱 userImgUrls原始: ${userData['userImgUrls']} (类型: ${userData['userImgUrls'].runtimeType})');
        developer.log('🔐 extraData原始: ${userData['extraData']} (类型: ${userData['extraData'].runtimeType})');
        developer.log('🏷️ userTags原始: ${userData['userTags']} (类型: ${userData['userTags'].runtimeType})');
      }

      if (userData != null && isLoggedIn) {
        _currentUser.value = UserData.fromJson(userData);
        _isLoggedIn.value = true;
        
        developer.log('✅ 从本地存储加载用户信息成功: ${_currentUser.value?.username}');
        developer.log('🔍 解析后的用户数据:');
        developer.log('  📱 用户ID: ${_currentUser.value?.userid}');
        developer.log('  👤 用户名: ${_currentUser.value?.username}');
        developer.log('  🖼️ 相册数据: ${_currentUser.value?.userImgUrls} (数量: ${_currentUser.value?.userImgUrls?.length ?? 0})');
        developer.log('  🏷️ 用户标签: ${_currentUser.value?.userTags} (数量: ${_currentUser.value?.userTags?.length ?? 0})');
        developer.log('  🔐 extraData存在: ${_currentUser.value?.extraData != null}');
        
        if (_currentUser.value?.extraData != null) {
          final realNameAuth = _currentUser.value!.extraData!['realNameAuth'];
          developer.log('  🆔 realNameAuth存在: ${realNameAuth != null}');
          if (realNameAuth != null) {
            developer.log('    📝 realNameAuth详细: $realNameAuth');
          }
        }
      } else {
        developer.log('⚠️ 本地存储条件不满足:');
        developer.log('  userData为null: ${userData == null}');
        developer.log('  未登录: ${!isLoggedIn}');
      }
      
      developer.log('🔍 ================ 本地存储加载结束 ================');
    } catch (e) {
      developer.log('💥 加载本地用户信息失败: $e');
      developer.log('💥 错误详细: ${e.toString()}');
      clearUser();
    }
  }

  /// 保存用户信息到本地存储
  void _saveUserToStorage() {
    try {
      if (_currentUser.value != null) {
        _storage.write(_userInfoKey, _currentUser.value!.toJson());
        _storage.write(_loginStatusKey, true);
        developer.log('用户信息保存到本地存储成功');
      }
    } catch (e) {
      developer.log('保存用户信息到本地存储失败: $e');
    }
  }

  /// 通过手机号获取用户信息
  Future<bool> fetchUserInfo(String userPhone) async {
    try {
      developer.log('开始获取用户信息: $userPhone');

      final response = await UserApi.checkPhone(userPhone: userPhone);
      
      if (response.isSuccess && response.exists && response.data != null) {
        // 设置用户信息
        setUser(response.data!);
        
        developer.log('✅ 用户信息获取成功: ${response.data!.username}');
        return true;
      } else {
        developer.log('❌ 用户信息获取失败: ${response.message}');
        return false;
      }
    } catch (e) {
      developer.log('💥 获取用户信息异常: $e');
      return false;
    }
  }

  /// 设置用户信息
  void setUser(UserData userData) {
    _currentUser.value = userData;
    _isLoggedIn.value = true;
    _saveUserToStorage();
    
    developer.log('🔄 =============== 用户信息设置详细日志 ===============');
    developer.log('✅ 用户信息已设置: ${userData.username}');
    developer.log('  📱 用户ID: ${userData.userid}');
    developer.log('  💰 用户积分: ${userData.userPoints}');
    developer.log('  🆙 用户等级: ${userData.userLevel}');
    developer.log('  ❤️ 点赞数: ${userData.userLikes}');
    developer.log('  👥 粉丝数: ${userData.userFollowers}');
    developer.log('  🎂 年龄: ${userData.userAge}');
    developer.log('  ⚥ 性别: ${userData.userGender}');
    developer.log('  ✍️ 签名: ${userData.userSignature}');
    developer.log('  📞 手机号: ${userData.userPhone}');
    developer.log('  🏷️ 标签: ${userData.userTags}');
    developer.log('  🖼️ 头像: ${userData.userAvatarUrl}');
    developer.log('🔄 =============== 用户信息设置完成 ===============');
  }

  /// 更新用户信息
  void updateUser(UserData userData) {
    _currentUser.value = userData;
    _saveUserToStorage();
    
    developer.log('🔄 =============== 用户信息更新详细日志 ===============');
    developer.log('✅ 用户信息已更新: ${userData.username}');
    developer.log('  📱 用户ID: ${userData.userid}');
    developer.log('  💰 用户积分: ${userData.userPoints}');
    developer.log('  🆙 用户等级: ${userData.userLevel}');
    developer.log('  ❤️ 点赞数: ${userData.userLikes}');
    developer.log('  👥 粉丝数: ${userData.userFollowers}');
    developer.log('  🖼️ 当前头像URL: ${userData.userAvatarUrl}');
    developer.log('  🏷️ 标签: ${userData.userTags}');
    developer.log('🔄 =============== 用户信息更新完成 ===============');
  }

  /// 更新用户积分
  void updateUserPoints(int points) {
    if (_currentUser.value != null) {
      final updatedUser = UserData(
        userid: _currentUser.value!.userid,
        userPhone: _currentUser.value!.userPhone,
        userEmail: _currentUser.value!.userEmail,
        userCode: _currentUser.value!.userCode,
        username: _currentUser.value!.username,
        userAvatarUrl: _currentUser.value!.userAvatarUrl,
        userData: _currentUser.value!.userData,
        userAge: _currentUser.value!.userAge,
        userGender: _currentUser.value!.userGender,
        userSignature: _currentUser.value!.userSignature,
        userTags: _currentUser.value!.userTags,
        userLikes: _currentUser.value!.userLikes,
        userFollowers: _currentUser.value!.userFollowers,
        userPoints: points, // 更新积分
        userHobbies: _currentUser.value!.userHobbies,
        userCity: _currentUser.value!.userCity,
        userImgUrls: _currentUser.value!.userImgUrls,
        userFrequentPlaces: _currentUser.value!.userFrequentPlaces,
        userBirthday: _currentUser.value!.userBirthday,
        userLevel: _currentUser.value!.userLevel,
        status: _currentUser.value!.status,
        extraData: _currentUser.value!.extraData,
        createdAt: _currentUser.value!.createdAt,
        lastLogin: _currentUser.value!.lastLogin,
        updatedAt: _currentUser.value!.updatedAt,
      );
      updateUser(updatedUser);
    }
  }

  /// 清除用户信息(退出登录) - 增强版本，参考MyApplication2的完整清理逻辑
  void clearUser() {
    try {
      developer.log('🚀 =============== 开始用户信息完整清理 ===============');
      
      // 保存当前用户手机号（参考MyApplication2的逻辑）
      final currentUserPhone = _currentUser.value?.userPhone ?? '';
      
      // 清除用户状态
      _currentUser.value = null;
      _isLoggedIn.value = false;
      
      // 🔥 参考MyApplication2：清除所有用户相关的本地存储数据
      _storage.erase(); // 清空所有GetStorage数据
      
      // 🔥 参考MyApplication2：保留必要的数据（手机号和首次使用标记）
      if (currentUserPhone.isNotEmpty) {
        _storage.write('userPhone', currentUserPhone);
        developer.log('📱 保留用户手机号: $currentUserPhone');
      }
      _storage.write('isFirstInput', '1');
      _storage.write('ifFirstAgree', '1');
      
      // 🔥 清理活动申请通知状态
      _storage.write('ifInputActivity', '0');
      
      developer.log('✅ 用户信息完整清理完成');
      developer.log('📋 保留数据: 手机号=${currentUserPhone.isNotEmpty ? "已保留" : "无"}, 首次标记=已重置');
      
    } catch (e) {
      developer.log('💥 清除用户信息异常: $e');
      // 即使异常也要确保基本清理
      _currentUser.value = null;
      _isLoggedIn.value = false;
    }
  }

  /// 检查是否需要重新登录
  bool needReLogin() {
    return !_isLoggedIn.value || _currentUser.value == null;
  }

  /// 刷新用户信息
  Future<bool> refreshUserInfo() async {
    if (_currentUser.value?.userPhone != null) {
      return await fetchUserInfo(_currentUser.value!.userPhone!);
    }
    return false;
  }

  /// 更新用户信息到服务器（与MyApplication2保持完全一致）
  Future<bool> updateUserInfoToServer({
    String? username,
    String? userSignature,
    String? userGender,
    String? userBirthday, // 📝 修改：使用生日而非年龄，与MyApplication2一致
    String? userFrequentPlaces,
    String? userAvatarUrl, // 📝 新增：头像URL参数
    List<String>? userHobbies, // 📝 新增：用户爱好列表，支持自定义选择
    List<String>? userImgUrls, // 📝 新增：相册图片URLs
  }) async {
    if (_currentUser.value?.userPhone == null) {
      developer.log('❌ 用户未登录，无法更新信息');
      return false;
    }

    try {
      developer.log('开始更新用户信息到服务器');
      
      // 🔥 修复：支持用户自定义选择爱好（与MyApplication2一致）
      // 如果没有传递爱好参数，不更新爱好；如果传递了，使用传递的爱好
      final shouldUpdateHobbies = userHobbies != null;
      final finalHobbies = shouldUpdateHobbies ? userHobbies : null;
      
      developer.log('🍽️ 爱好更新策略: ${shouldUpdateHobbies ? "更新为 $finalHobbies" : "不更新爱好"}');
      
      final response = await UserApi.updateUserInfo(
        userPhone: _currentUser.value!.userPhone!,
        username: username,
        userSignature: userSignature,
        userGender: userGender,
        userBirthday: userBirthday,
        userFrequentPlaces: userFrequentPlaces,
        userHobbies: finalHobbies, // 🔥 使用用户选择的爱好
        userAvatarUrl: userAvatarUrl,
        userImgUrls: userImgUrls,
      );

      if (response.isSuccess && response.data != null) {
        // 更新本地用户信息
        updateUser(response.data!);
        developer.log('✅ 用户信息更新成功: ${response.message}');
        return true;
      } else {
        developer.log('❌ 用户信息更新失败: ${response.message}');
        return false;
      }
    } catch (e) {
      developer.log('💥 更新用户信息异常: $e');
      return false;
    }
  }

  /// 上传用户头像
  Future<bool> uploadUserAvatar({
    required String imagePath,
    Function(int sent, int total)? onProgress,
  }) async {
    if (_currentUser.value?.userPhone == null) {
      developer.log('❌ 用户未登录，无法上传头像');
      return false;
    }

    try {
      developer.log('开始上传用户头像: $imagePath');
      
      final response = await UserApi.uploadUserImage(
        userId: _currentUser.value!.userid,
        filePath: imagePath,
        onProgress: onProgress,
      );

      if (response.isSuccess) {
        developer.log('✅ 头像上传成功: ${response.message}');
        
        // 如果响应中包含新的头像URL，需要调用update接口同步到服务器
        if (response.imageUrl != null && _currentUser.value != null) {
          final newAvatarUrl = response.imageUrl!;
          developer.log('✅ 上传成功，新头像URL: $newAvatarUrl');
          
          // 立即更新本地头像URL，确保UI马上显示新头像
          final updatedUser = UserData(
            userid: _currentUser.value!.userid,
            userPhone: _currentUser.value!.userPhone,
            userEmail: _currentUser.value!.userEmail,
            userCode: _currentUser.value!.userCode,
            username: _currentUser.value!.username,
            userAvatarUrl: newAvatarUrl, // 使用新的头像URL
            userData: _currentUser.value!.userData,
            userAge: _currentUser.value!.userAge,
            userGender: _currentUser.value!.userGender,
            userSignature: _currentUser.value!.userSignature,
            userTags: _currentUser.value!.userTags,
            userLikes: _currentUser.value!.userLikes,
            userFollowers: _currentUser.value!.userFollowers,
            userPoints: _currentUser.value!.userPoints,
            userHobbies: _currentUser.value!.userHobbies,
            userCity: _currentUser.value!.userCity,
            userImgUrls: _currentUser.value!.userImgUrls,
            userFrequentPlaces: _currentUser.value!.userFrequentPlaces,
            userBirthday: _currentUser.value!.userBirthday,
            userLevel: _currentUser.value!.userLevel,
            status: _currentUser.value!.status,
            extraData: _currentUser.value!.extraData,
            createdAt: _currentUser.value!.createdAt,
            lastLogin: _currentUser.value!.lastLogin,
            updatedAt: _currentUser.value!.updatedAt,
          );
          
          // 立即更新本地用户信息，确保UI响应
          updateUser(updatedUser);
          developer.log('✅ 本地头像URL已立即更新: $newAvatarUrl');
          
          // 关键修复：调用update接口将新头像URL同步到服务器
          try {
            developer.log('🔄 正在将新头像URL同步到服务器...');
            final updateResponse = await UserApi.updateUserInfo(
              userPhone: _currentUser.value!.userPhone!,
              userAvatarUrl: newAvatarUrl, // 更新头像URL到服务器
            );
            
            if (updateResponse.isSuccess) {
              developer.log('✅ 头像URL已成功同步到服务器');
              // 如果服务器返回了更新后的用户数据，使用它
              if (updateResponse.data != null) {
                updateUser(updateResponse.data!);
                developer.log('✅ 使用服务器返回的最新用户数据');
              }
            } else {
              developer.log('⚠️ 头像URL同步到服务器失败: ${updateResponse.message}');
            }
          } catch (syncError) {
            developer.log('❌ 同步头像URL到服务器异常: $syncError');
          }
        }
        
        return true;
      } else {
        developer.log('❌ 头像上传失败: ${response.message}');
        return false;
      }
    } catch (e) {
      developer.log('💥 上传头像异常: $e');
      return false;
    }
  }

  // ================== 相册管理功能 ==================
  
  /// 上传相册图片
  Future<bool> uploadAlbumImage({
    required String imagePath,
    Function(int sent, int total)? onProgress,
  }) async {
    if (_currentUser.value?.userPhone == null) {
      developer.log('❌ 用户未登录，无法上传相册图片');
      return false;
    }

    try {
      developer.log('开始上传相册图片: $imagePath');
      
      final response = await UserApi.uploadUserImage(
        userId: _currentUser.value!.userid,
        filePath: imagePath,
        onProgress: onProgress,
      );

      if (response.isSuccess && response.imageUrl != null) {
        final newImageUrl = response.imageUrl!;
        developer.log('✅ 相册图片上传成功，URL: $newImageUrl');
        
        // 更新本地用户信息，添加新图片到相册
        final currentImages = List<String>.from(_currentUser.value!.userImgUrls ?? []);
        currentImages.add(newImageUrl);
        
        final updatedUser = UserData(
          userid: _currentUser.value!.userid,
          userPhone: _currentUser.value!.userPhone,
          userEmail: _currentUser.value!.userEmail,
          userCode: _currentUser.value!.userCode,
          username: _currentUser.value!.username,
          userAvatarUrl: _currentUser.value!.userAvatarUrl,
          userData: _currentUser.value!.userData,
          userAge: _currentUser.value!.userAge,
          userGender: _currentUser.value!.userGender,
          userSignature: _currentUser.value!.userSignature,
          userTags: _currentUser.value!.userTags,
          userLikes: _currentUser.value!.userLikes,
          userFollowers: _currentUser.value!.userFollowers,
          userPoints: _currentUser.value!.userPoints,
          userHobbies: _currentUser.value!.userHobbies,
          userCity: _currentUser.value!.userCity,
          userImgUrls: currentImages, // 更新相册图片列表
          userFrequentPlaces: _currentUser.value!.userFrequentPlaces,
          userBirthday: _currentUser.value!.userBirthday,
          userLevel: _currentUser.value!.userLevel,
          status: _currentUser.value!.status,
          extraData: _currentUser.value!.extraData,
          createdAt: _currentUser.value!.createdAt,
          lastLogin: _currentUser.value!.lastLogin,
          updatedAt: _currentUser.value!.updatedAt,
        );
        
        // 立即更新本地用户信息
        updateUser(updatedUser);
        developer.log('✅ 本地相册图片已立即更新');
        
        // 将更新后的相册同步到服务器
        try {
          developer.log('🔄 正在将新相册同步到服务器...');
          final updateResponse = await UserApi.updateUserInfo(
            userPhone: _currentUser.value!.userPhone!,
            userImgUrls: currentImages, // 🔥 修复：传递更新后的相册图片列表
          );
          
          if (updateResponse.isSuccess) {
            developer.log('✅ 相册同步到服务器成功');
            // 如果服务器返回了更新后的用户数据，使用它
            if (updateResponse.data != null) {
              updateUser(updateResponse.data!);
              developer.log('✅ 使用服务器返回的最新用户数据');
            }
          } else {
            developer.log('⚠️ 相册同步到服务器失败: ${updateResponse.message}');
          }
        } catch (syncError) {
          developer.log('❌ 同步相册到服务器异常: $syncError');
        }
        
        return true;
      } else {
        developer.log('❌ 相册图片上传失败: ${response.message}');
        return false;
      }
    } catch (e) {
      developer.log('💥 上传相册图片异常: $e');
      return false;
    }
  }
  
  /// 删除相册图片
  Future<bool> removeAlbumImage(int index) async {
    if (_currentUser.value?.userPhone == null) {
      developer.log('❌ 用户未登录，无法删除相册图片');
      return false;
    }
    
    try {
      final currentImages = List<String>.from(_currentUser.value!.userImgUrls ?? []);
      if (index < 0 || index >= currentImages.length) {
        developer.log('❌ 无效的图片索引: $index');
        return false;
      }
      
      developer.log('开始删除相册图片，索引: $index');
      
      // 从列表中移除指定索引的图片
      currentImages.removeAt(index);
      
      // 更新本地用户信息
      final updatedUser = UserData(
        userid: _currentUser.value!.userid,
        userPhone: _currentUser.value!.userPhone,
        userEmail: _currentUser.value!.userEmail,
        userCode: _currentUser.value!.userCode,
        username: _currentUser.value!.username,
        userAvatarUrl: _currentUser.value!.userAvatarUrl,
        userData: _currentUser.value!.userData,
        userAge: _currentUser.value!.userAge,
        userGender: _currentUser.value!.userGender,
        userSignature: _currentUser.value!.userSignature,
        userTags: _currentUser.value!.userTags,
        userLikes: _currentUser.value!.userLikes,
        userFollowers: _currentUser.value!.userFollowers,
        userPoints: _currentUser.value!.userPoints,
        userHobbies: _currentUser.value!.userHobbies,
        userCity: _currentUser.value!.userCity,
        userImgUrls: currentImages, // 更新相册图片列表
        userFrequentPlaces: _currentUser.value!.userFrequentPlaces,
        userBirthday: _currentUser.value!.userBirthday,
        userLevel: _currentUser.value!.userLevel,
        status: _currentUser.value!.status,
        extraData: _currentUser.value!.extraData,
        createdAt: _currentUser.value!.createdAt,
        lastLogin: _currentUser.value!.lastLogin,
        updatedAt: _currentUser.value!.updatedAt,
      );
      
      // 立即更新本地用户信息
      updateUser(updatedUser);
      developer.log('✅ 本地相册图片已删除');
      
      // 将更新后的相册同步到服务器
      try {
        developer.log('🔄 正在将删除操作同步到服务器...');
        final updateResponse = await UserApi.updateUserInfo(
          userPhone: _currentUser.value!.userPhone!,
          userImgUrls: currentImages, // 🔥 修复：传递更新后的相册图片列表
        );
        
        if (updateResponse.isSuccess) {
          developer.log('✅ 删除操作同步到服务器成功');
          if (updateResponse.data != null) {
            updateUser(updateResponse.data!);
            developer.log('✅ 使用服务器返回的最新用户数据');
          }
        } else {
          developer.log('⚠️ 删除操作同步到服务器失败: ${updateResponse.message}');
        }
      } catch (syncError) {
        developer.log('❌ 同步删除操作到服务器异常: $syncError');
      }
      
      return true;
    } catch (e) {
      developer.log('💥 删除相册图片异常: $e');
      return false;
    }
  }
  
  /// 替换相册图片
  Future<bool> replaceAlbumImage({
    required int index,
    required String imagePath,
    Function(int sent, int total)? onProgress,
  }) async {
    if (_currentUser.value?.userPhone == null) {
      developer.log('❌ 用户未登录，无法替换相册图片');
      return false;
    }
    
    try {
      final currentImages = List<String>.from(_currentUser.value!.userImgUrls ?? []);
      if (index < 0 || index >= currentImages.length) {
        developer.log('❌ 无效的图片索引: $index');
        return false;
      }
      
      developer.log('开始替换相册图片，索引: $index, 新图片: $imagePath');
      
      // 先上传新图片
      final response = await UserApi.uploadUserImage(
        userId: _currentUser.value!.userid,
        filePath: imagePath,
        onProgress: onProgress,
      );

      if (response.isSuccess && response.imageUrl != null) {
        final newImageUrl = response.imageUrl!;
        developer.log('✅ 新图片上传成功，URL: $newImageUrl');
        
        // 替换指定索引的图片
        currentImages[index] = newImageUrl;
        
        // 更新本地用户信息
        final updatedUser = UserData(
          userid: _currentUser.value!.userid,
          userPhone: _currentUser.value!.userPhone,
          userEmail: _currentUser.value!.userEmail,
          userCode: _currentUser.value!.userCode,
          username: _currentUser.value!.username,
          userAvatarUrl: _currentUser.value!.userAvatarUrl,
          userData: _currentUser.value!.userData,
          userAge: _currentUser.value!.userAge,
          userGender: _currentUser.value!.userGender,
          userSignature: _currentUser.value!.userSignature,
          userTags: _currentUser.value!.userTags,
          userLikes: _currentUser.value!.userLikes,
          userFollowers: _currentUser.value!.userFollowers,
          userPoints: _currentUser.value!.userPoints,
          userHobbies: _currentUser.value!.userHobbies,
          userCity: _currentUser.value!.userCity,
          userImgUrls: currentImages, // 更新相册图片列表
          userFrequentPlaces: _currentUser.value!.userFrequentPlaces,
          userBirthday: _currentUser.value!.userBirthday,
          userLevel: _currentUser.value!.userLevel,
          status: _currentUser.value!.status,
          extraData: _currentUser.value!.extraData,
          createdAt: _currentUser.value!.createdAt,
          lastLogin: _currentUser.value!.lastLogin,
          updatedAt: _currentUser.value!.updatedAt,
        );
        
        // 立即更新本地用户信息
        updateUser(updatedUser);
        developer.log('✅ 本地相册图片已替换');
        
        // 将更新后的相册同步到服务器
        try {
          developer.log('🔄 正在将替换操作同步到服务器...');
          final updateResponse = await UserApi.updateUserInfo(
            userPhone: _currentUser.value!.userPhone!,
            userImgUrls: currentImages, // 🔥 修复：传递更新后的相册图片列表
          );
          
          if (updateResponse.isSuccess) {
            developer.log('✅ 替换操作同步到服务器成功');
            if (updateResponse.data != null) {
              updateUser(updateResponse.data!);
              developer.log('✅ 使用服务器返回的最新用户数据');
            }
          } else {
            developer.log('⚠️ 替换操作同步到服务器失败: ${updateResponse.message}');
          }
        } catch (syncError) {
          developer.log('❌ 同步替换操作到服务器异常: $syncError');
        }
        
        return true;
      } else {
        developer.log('❌ 新图片上传失败: ${response.message}');
        return false;
      }
    } catch (e) {
      developer.log('💥 替换相册图片异常: $e');
      return false;
    }
  }

  /// 获取格式化的用户信息字符串
  String getUserInfoString() {
    if (_currentUser.value == null) return '未登录';
    
    final user = _currentUser.value!;
    return '''
用户信息:
  用户ID: ${user.userid}
  昵称: ${user.username}
  手机号: ${user.userPhone}
  等级: ${user.userLevel}
  积分: ${user.userPoints}
  签名: ${user.userSignature}
  标签: ${user.userTags}
  创建时间: ${user.createdAt}
  更新时间: ${user.updatedAt}
''';
  }

  /// 提交实名认证
  Future<RealnameAuthResponse> submitRealnameAuth({
    required String realName,
    required String idCardNo,
  }) async {
    if (_currentUser.value == null) {
      developer.log('❌ 用户未登录，无法进行实名认证');
      return RealnameAuthResponse(
        status: 'error',
        message: '用户未登录，请先登录',
      );
    }

    try {
      developer.log('开始提交实名认证');
      developer.log('用户ID: ${_currentUser.value!.userid}');
      developer.log('真实姓名: $realName');
      developer.log('身份证号: ${idCardNo.replaceRange(6, idCardNo.length - 4, '****')}'); // 脱敏显示
      
      final response = await UserApi.realnameAuth(
        userId: _currentUser.value!.userid,
        realName: realName,
        idCardNo: idCardNo,
      );

      if (response.isSuccess) {
        developer.log('✅ 实名认证提交成功');
        developer.log('认证状态: ${response.authStatusDescription}');
        developer.log('是否已认证: ${response.isVerified}');
        developer.log('流程ID: ${response.flowId}');
        developer.log('认证时间: ${response.authTime}');
        developer.log('脱敏身份证: ${response.maskedIdCard}');
        
        // 🔥 修复：认证成功后更新用户信息中的实名认证状态
        if (response.isVerified && _currentUser.value != null) {
          developer.log('🔄 更新用户实名认证状态到本地');
          
          // 更新用户的extraData中的实名认证信息
          final extraData = Map<String, dynamic>.from(_currentUser.value!.extraData ?? {});
          extraData['realNameAuth'] = {
            'verified': true,
            'name': realName,
            'idCardNo': response.maskedIdCard,
            'authTime': response.authTime,
            'status': response.data?.authStatus ?? 2,
            'message': response.message,
            'flowId': response.flowId,
          };
          
          // 创建新的 UserData 实例，因为 extraData 是 final 字段
          final currentUser = _currentUser.value!;
          final updatedUser = UserData(
            userid: currentUser.userid,
            userPhone: currentUser.userPhone,
            userEmail: currentUser.userEmail,
            userCode: currentUser.userCode,
            username: currentUser.username,
            userAvatarUrl: currentUser.userAvatarUrl,
            userData: currentUser.userData,
            userAge: currentUser.userAge,
            userGender: currentUser.userGender,
            userSignature: currentUser.userSignature,
            userTags: currentUser.userTags,
            userLikes: currentUser.userLikes,
            userFollowers: currentUser.userFollowers,
            userPoints: currentUser.userPoints,
            userHobbies: currentUser.userHobbies,
            userCity: currentUser.userCity,
            userImgUrls: currentUser.userImgUrls,
            userFrequentPlaces: currentUser.userFrequentPlaces,
            userBirthday: currentUser.userBirthday,
            userLevel: currentUser.userLevel,
            status: currentUser.status,
            extraData: extraData, // 使用更新后的 extraData
            createdAt: currentUser.createdAt,
            lastLogin: currentUser.lastLogin,
            updatedAt: currentUser.updatedAt,
          );
          
          // 更新当前用户
          _currentUser.value = updatedUser;
          
          developer.log('✅ 用户实名认证状态更新完成');
          developer.log('📝 认证信息: ${extraData['realNameAuth']}');
        }
      } else {
        developer.log('❌ 实名认证提交失败: ${response.message}');
      }

      return response;
    } catch (e) {
      developer.log('💥 提交实名认证异常: $e');
      return RealnameAuthResponse(
        status: 'error',
        message: '实名认证异常: ${e.toString()}',
      );
    }
  }

  /// 查询实名认证状态
  Future<RealnameAuthResponse> checkRealnameAuthStatus() async {
    if (_currentUser.value == null) {
      developer.log('❌ 用户未登录，无法查询实名认证状态');
      return RealnameAuthResponse(
        status: 'error',
        message: '用户未登录，请先登录',
      );
    }

    try {
      developer.log('开始查询实名认证状态');
      
      // 由于API要求必要参数，暂时使用默认值查询状态
      // 实际项目中应该有专门的状态查询接口
      final response = await UserApi.realnameAuth(
        userId: _currentUser.value!.userid,
        realName: '查询状态', // 使用占位符，避免API参数验证失败
        idCardNo: '000000000000000000', // 使用占位符
      );

      if (response.isSuccess) {
        developer.log('✅ 实名认证状态查询成功');
        developer.log('认证状态: ${response.authStatusDescription}');
        developer.log('是否已认证: ${response.isVerified}');
        developer.log('脱敏身份证: ${response.maskedIdCard}');
        developer.log('认证时间: ${response.authTime}');
      } else {
        developer.log('❌ 实名认证状态查询失败: ${response.message}');
      }

      return response;
    } catch (e) {
      developer.log('💥 查询实名认证状态异常: $e');
      return RealnameAuthResponse(
        status: 'error',
        message: '查询认证状态异常: ${e.toString()}',
      );
    }
  }

  @override
  void onClose() {
    developer.log('UserService销毁');
    super.onClose();
  }
}
